package com.shockweb.common.utils;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;

/**
 * 配置文件读取工具类
 * 
 * @author 彭明华
 * 2018年1月3日 创建
 */
public class PropertyFile {
	/**
	 * 读取Property文件
	 * @param propFilePath
	 * @return Map
	 * @throws IOException
	 */
	public static Map<String,String> read(String propFilePath) throws IOException{
		InputStream in = null;
		try{
			Properties prop = new Properties();
			Map<String,String> map = new HashMap<String,String>();
			//读取属性文件
			in = new FileInputStream(propFilePath);
			prop.load(in);     ///加载属性列表
			Iterator<String> it = prop.stringPropertyNames().iterator();
			while(it.hasNext()){
				String key=it.next();
				map.put(key, prop.getProperty(key));
			}
			if(map.isEmpty()){
				return null;
			}else{
				return map;
			}
		}finally{
			if(in!=null){
				try {
					in.close();
				} catch (IOException e) {

				}
			}
		}
	}
	
	
	/**
	 * 写入Property文件
	 * @param propFilePath
	 * @param data
	 * @throws IOException
	 */
	public static void write(String propFilePath,Map<String,String> data) throws IOException{
		OutputStream out = null;
		try{
			Properties  prop = new Properties();
			///保存属性到roperties文件
			out = new FileOutputStream(propFilePath);
			Iterator<Entry<String,String>> it = data.entrySet().iterator();
			while(it.hasNext()){
				Entry<String,String> entry = it.next();
				prop.setProperty(entry.getValue(), entry.getValue());
			}
			prop.store(out, "The New properties file");
			out.flush();
		}finally{
			if(out!=null){
				try {
					out.close();
				} catch (IOException e) {

				}
			}
		}
	}
}
